import React, { FC, useState, useEffect, useRef, useMemo } from "react";
import styles from "./common.module.scss";
import QuestionCard from "../../components/QuestionCard";
import QuestionSearch from "../../components/QuestionSearch";
import { Typography, Spin, Empty } from "antd";
import { useTitle, useDebounceFn, useRequest } from "ahooks";
import { useSearchParams } from "react-router-dom";
// import { getToken } from "../../storage/userToken";
// import { getQuestionsList } from "../../utils/api";

import { getQuestionsList } from "../../utils/api";
import { LIST_PAGESIZE, LIST_SEARCH_PARAM_KEY } from "../../constant";

const { Title } = Typography;
const List: FC = () => {
  useTitle("星问卷-我的问卷");
  // const { data = {}, loading } = useLoadingQuestionList({})
  // const { list = [], total = 0 } = data;
  // const questionList = list;
  const [searchParams] = useSearchParams();
  const [questionList, setQuestionList] = useState([]);
  const [page, setPage] = useState(1);
  // const [loading,setLoading]=useState()
  const [total, setTotal] = useState(0);
  const haveLoadMore = total > questionList.length;
  const footerRef = useRef<HTMLDivElement>(null);
  //是否开始防抖(防抖有延迟)
  const [started, setStarted] = useState(false);
  const keyword = searchParams.get(LIST_SEARCH_PARAM_KEY) || "";
  const { run: loadMore, loading } = useRequest(
    async () => {
      const data = await getQuestionsList({
        page,
        pageSize: LIST_PAGESIZE,
        keyword: keyword,
      });
      return data;
    },
    {
      manual: true,
      onSuccess(res) {
        const { list = [], total = 0 } = res;
        setQuestionList(questionList.concat(list));
        setTotal(total);
        setPage(page + 1);
      },
    }
  );
  //防抖
  const { run: LoadMore } = useDebounceFn(
    () => {
      const footerElem = footerRef.current;
      if (footerElem == null) return;
      const FootDom = footerElem.getBoundingClientRect();
      if (FootDom == null) return;
      if (FootDom.bottom <= document.body.clientHeight) {
        loadMore();
        setStarted(true);
      }
    },
    {
      wait: 1000,
    }
  );
  useEffect(() => {    
    LoadMore();
  }, [searchParams]);
  useEffect(() => {
    if (haveLoadMore) {
      window.addEventListener("scroll", LoadMore);
    }
    return () => {
      window.removeEventListener("scroll", LoadMore);
    };
  }, [searchParams, haveLoadMore]);
  useEffect(() => {
    //keyword变化,初始化信息
    setStarted(false)
    setQuestionList([]);
    setTotal(0);
    setPage( 1);
  }, [keyword])
  //useMemo缓存,函数的执行
  const LoadingFooter = useMemo(() => {
    if (!started || loading) return <Spin />;
    if (total == 0) return <Empty description="暂无数据" />;
    if (!haveLoadMore) return <span>没有更多...</span>;
    return <span>加载更多</span>;
  },[started,loading,haveLoadMore]);
  return (
    <>
      <div className={styles.header}>
        <div className={styles.left}>
          <Title level={3}>我的问卷</Title>
        </div>
        <div className={styles.right}>
          <QuestionSearch />
        </div>
      </div>
      <div className={styles.content}>
        {/* { loading && (
          <div style={{ textAlign: "center" }}>
            <Spin />
          </div>
        )} */}

        {questionList.length > 0 &&
          questionList.map((item: any) => {
            const { _id } = item;
            return <QuestionCard key={_id} {...item} />;
          })}
      </div>
      <div className={styles.footer}>
        <div ref={footerRef}>{LoadingFooter}</div>
      </div>
    </>
  );
};
export default List;
